/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.opprua.dss.adapter;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.opprua.dss.application.RBase;
import org.opprua.dss.application.ServerRunner;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * TODO: add Java doc
 * 
 * Prepared for first commit: 22.02.2007
 * 
 * @author Lin Li
 */
public class OppruaSpringServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private static Map<String, RequestLead> reqs = Collections
              .synchronizedMap(new HashMap<String, RequestLead>());
  private ServerRunner app = null;

  protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    WebApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(request
                .getSession().getServletContext());
    RequestLead rl = new RequestLead(request, response, con);
    reqs.put(Thread.currentThread().getName(), rl);
    try {
      if(app == null) {
        app = new ServerRunner();
      }
      app.run();
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    doPost(request, response);
  }

  public static RBase getLead() {
    return reqs.get(Thread.currentThread().getName());
  }
}
